// pages/user_end/payorder/payorder.js
const app = getApp();
const request = require('../../../utils/request.js');
const url = require('../../../utils/url.js');
const cookie = require('../../../utils/cookie.js');
const WxParse = require('../../../wxParse/wxParse.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {	  
	countdown: 5,
    id: 0,
	area:'',
	bytype:'',
	region:'',
    address_id: 0,
    coupon_id: 0,
    servicenums: 1,
    isReserve: 0, //是否选择预约日期
    worker_avatar: '',
    worker_name: '',
    order: [],
    worklist: [],
	retentionlist:[],
    worker_id: 0,
    show: false,
    show1: false,
    nindex: 0,
    datelist: [],
    timelist: [],
    timelist2: [],
    reserveDate: "", //预约日期
    reserveShow: "", //服务开始时间
    reserveTime: 0,
    service_category_id: 0,
    service_desc: "",
    service_desc_images: [],
    remark: "",
    active: 1,
    imgs: [],
    picList: [],
    service_time_unit: 30, //服务时间区间
    service_multiple: false, //单选
    cnum: 0, //选中数
    token: '',
    checkContract: 0, //选择合同
    agreement:true,
	buttonDisabled:true,
	categoryname:'',
	tax_title:'',
	tax_no:'',
	good:'',
	index:0,
	btnshow:true,
	checked:false,
	fwsj:false,
	fwpc:false,
	byfzlb:false,
	fwsjtext:'',
	fwpctext:'',
  tax_email:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id: options.id,
	  categoryname:options.categoryname
    })
    var that = this;
    cookie.getCookie('userInfo', function (res) {
      if (res) {
        var etime = Date.parse(new Date()) / 1000;
        
        if (etime < res.expiretime) {
          that.setData({
            login: 1,
            token: res.token
          })
		  that.getgoodlist();
		  that.getcontent();
          that.getDatelist();
          that.getOrderShow();
        }
      }
    })

   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  changeAgreement(){
      this.setData({
          agreement:false
      })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    if (that.data.token) {
      that.getOrderShow();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  changetaxtitle(e) {
      this.setData({
          tax_title: e.detail.value
      })
  },
choseFwsj(e)
{
	var that = this;
		 var fwsjtext = e.currentTarget.dataset.fwsj;
	if(fwsjtext=='一次性')
	{
	
		that.setData({
			  fwpc:false
		})
	}
	else
	{
		that.setData({
			  fwpc:true
		})
	}
	this.setData({
	  fwsjtext: fwsjtext
	})
},
choseFwpc(e)
{
	var that = this;
		 var fwpctext = e.currentTarget.dataset.fwpc;
	
	this.setData({
	  fwpctext: fwpctext
	})
},
  choseArea(e) {
	
    this.setData({
      area: e.detail.value
    })
},

 chosebytype(e) {
    this.setData({
      bytype: e.detail.value
    })
},
  changetaxno(e) {
      this.setData({
          tax_no: e.detail.value
      })
  },
  changemail(e) {
    this.setData({
        tax_email: e.detail.value
    })
},
  getcontent(){
	  var that = this;
	  wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
	  
	  request.request('https://mcc.huotukj.com/index.php/api/xiservice.service_category/ordercontract', {}, url.REQUEST_METHOD_GET).then((res) => {
	    wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
	    if(res.data.code==1){
	      that.setData({
	        info:res.data.data
	      })
	      if(!res.data.data){
	       wx.showToast({
	         title:'该文章不存在!',
	         icon:'none'
	       });			
	       setTimeout(function(){
	         wx.navigateBack({
	           delta:1
	         })
	       },1500)							 
	      }
	      // wx.setNavigationBarTitle({
	      //   title: res.data.data.name,
	      // });
	      let content = res.data.data.content;
		  console.log(content);
	      WxParse.wxParse('htcontent', 'html', content, that, 0)
		  // that.data.countdownInterval = setInterval(that.countdownTimer, 3000);
		 that.countdownTimer();
	    }
	  })  
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  
    countdownTimer: function() {
      const that = this;
      let countdown = that.data.countdown;  
	  // 设置定时器
	  let timer = setInterval(function() {
	    countdown--;	    
		that.setData({
		  countdown: countdown
		});
		console.log(that.data.countdown);
	    // 当倒计时结束时
	    if (countdown <= 0) {
	      clearInterval(timer);
	     that.setData({
	       countdown: 0,
	       buttonDisabled: false
	     });
	    }
	  }, 1000);  
	  
     
    },
  choseTime: function () {
    this.setData({
      show1: true
    })
  },
  goAddress() {
    wx.navigateTo({
      url: '../address_chose/address_chose?type=1'
    })
  },
  open() {
    this.setData({
      show: true
    });
  },
  close() {
    this.setData({
      show: false,
      show1: false
    })
  },
  suretime() {
    if (this.data.isReserve == 0) {
      wx.showToast({
        title: '请选择时间',
        icon: 'none'
      });
      return false;
    }
    this.setData({
      show: false,
      show1: false
    })
  },
  choseReserve(e) {
    var time = e.currentTarget.dataset.timestamp;
    var check = e.currentTarget.dataset.checked;
    if (check == 0) {
      wx.showToast({
        title: '当前时间不可选',
        icon: 'none'
      });
      return false;
    }
    //遍历可选时间
    var that = this;
    var showtips = 0;
    //判断单选方式
    if (that.data.service_multiple == false) {
      that.data.timelist.forEach((item, index) => {
        var sItem = 'timelist[' + index + '].active';
        if (item.timestamp == time) {
          that.setData({
            [sItem]: 1
          })
        } else {
          that.setData({
            [sItem]: 0
          })
        }
      })
    } else {
      var count = 0;
      var length = that.data.timelist.length - 1;
      var arrIds = [];
      that.data.timelist.forEach((item, index) => {
        if (item.active == 1) {
          count++;
          arrIds.push(index);
        }
      });

      that.data.timelist.forEach((item, index) => {
        if (item.timestamp == time) {
          if (item.active == 1) {
            var active = 0;
            //判断连续性
            if (count > 0) {
              if (index == arrIds[0]) {
                var active = 0;

              } else if (index == arrIds[count - 1]) {
                var active = 0;

              } else {
                var active = 1;
                showtips = 2;
              }
            }

          } else {
            var active = 1;
            //判断连续性
            if (count > 0) {
              if (index == 0) {
                if (that.data.timelist[index + 1].active == 1) {
                  var active = 1;
                } else {
                  showtips = 1;
                  var active = 0;
                }
              } else if (index == length) {
                if (that.data.timelist[index - 1].active == 1) {
                  var active = 1;
                } else {
                  showtips = 1;
                  var active = 0;
                }
              } else {
                if (that.data.timelist[index + 1].active == 1 || that.data.timelist[index - 1].active == 1) {
                  var active = 1;
                } else {
                  showtips = 1;
                  var active = 0;
                }
              }
            }

          }
          //that.timelist[index].active = active;	
          var sItem = 'timelist[' + index + '].active';
          that.setData({
            [sItem]: active
          })
        }
      })
    }



    if (showtips == 1) {
      wx.showToast({
        title: '请先选择连续的时间!',
        icon: "none"
      })
    }
    if (showtips == 2) {
      wx.showToast({
        title: '请先选择取消开始时间!',
        icon: "none"
      })
    }
    //选择结果
    var chose = 0;
    var arrayIds = [];
    that.data.timelist.forEach((item, index) => {
      if (item.active == 1) {
        chose++;
        arrayIds.push(index);
      }
    });
    that.setData({
      cnum: chose
    })
    if (chose == 0) {
      that.setData({
        isReserve: 0,
        reserveShow: "",
        reserveTime: ""
      })
    } else {
      that.setData({
        isReserve: 1,
        reserveShow: that.data.reserveDate + ' ' + that.data.timelist[arrayIds[0]].start_time,
        reserveTime: that.data.timelist[arrayIds[0]].timestamp,
        worker_id: 0
      })
      that.getWorklist();
    }
  },
  chooseNav(e) {
    this.setData({
      nindex: e.target.dataset.current,
      isReserve: 0,
      reserveShow: "",
      reserveTime: "",
      reserveDate: e.target.dataset.date
    })
    this.getTimelist();
  },
  choseWorker() {
    if (!this.data.isReserve) {
      wx.showToast({
        title: '请先选择时间!',
        icon: "none"
      })
      return false;
    }
    if (this.data.worklist.length == 0) {
      wx.showToast({
        title: '暂无可选服务人员!',
        icon: "none"
      })
      return false;
    }
    this.setData({
      show: true
    })
  },
  choseWorkerId(e) {
    var id = e.currentTarget.dataset.uid;
    var name = e.currentTarget.dataset.name;
    var avatar = e.currentTarget.dataset.avatar;

    this.setData({
      worker_id: id,
      worker_name: name,
      worker_avatar: avatar,
      show: false
    })
    //更新价格
    this.getOrderShow();
  },
  getgoodlist:function(){
    var that = this;
    let param = {
      scoure: 'wxapp',
      id: that.data.id,
  	 token: that.data.token
    }
  
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.getgoodlist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
  	  console.log(res.data.data)
      if(res.data.code==1){
        that.setData({
          pxarray:res.data.data
        })
  	  that.data.good = that.data.pxarray[0];
  	  
       }
    })  							
  
  },
  
  getDatelist() {
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.getdatelist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
        that.setData({
          datelist: res.data.data,
          reserveDate: res.data.data[0].date
        })
      }
    })
  },
  bindAxb() {
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.bindAxb, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
        
      }
    })
  },
  getWorklist() {
    var that = this;
    if (!that.data.order.lat) {
      wx.showToast({
        title: '请选择地址!',
        icon: "none"
      })
      return false;
    }
    //选择结果
    var chose = 0;
    that.data.timelist.forEach((item, index) => {
      if (item.active == 1) {
        chose++;
      }
    });
    //判断类型
    var duration_time = 30;
    if (that.data.order.service.service_time_type == 1) {
      //固定时间
      duration_time = that.data.order.service.service_duration;
    } else if (that.data.order.service.service_time_type == 2) {
      //自选时长
      var unit = that.data.order.service.service_time_unit;
      duration_time = unit * chose;
    } else {
      //无时长
      duration_time = 30;
    }
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      lat: that.data.order.lat,
      lng: that.data.order.lng,
      reserve_time: that.data.reserveTime,
      duration_time: duration_time,
      service_category_id: that.data.service_category_id,
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.workerlist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
        that.setData({
          worklist: res.data.data
        })
      }
    })
  },
  getTimelist() {
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      date: that.data.reserveDate,
      service_time_unit: that.data.service_time_unit
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.commontime, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
        that.setData({
          timelist: res.data.data
        })
      }
    })
  },
  getOrderShow() {
	wx.requestSubscribeMessage({
    tmplIds: [
      'WCOeBpOwto_yU4ZM-hUmQePvbfY_lxKyaFK5Yi7nzao', //新订单通知
      'Cafgw0abMBtNXSJq8BDKhM_cNk0gydfQ845IywRo7KU', //报价更新通知
      'SOnJPXow5f0XddOr1jQ-3wdd6V1SifOHJMdQtPbJNo0' //被用户选择通知
    ],
	  success: (res) => {
	  },
	  fail: (res) => {
	  },
	})
    var that = this;
    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      address_id: that.data.address_id,
      coupon_id: that.data.coupon_id,
      worker_id: that.data.worker_id,
      service_id: that.data.id,
      remark: that.data.remark,
      servicenums: that.data.cnum,
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.ordershow, param, url.REQUEST_METHOD_GET).then((res) => {
		
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if (res.data.code == 1) {
		var fwpc = false;
		var fwsj=false;
		var byfzlb=false;
		if(res.data.data.service.service_category_id!=52 && res.data.data.service.service_category_id!=51)
		{
			fwpc=true;
			fwsj=true;
		}
		if(res.data.data.service.service_category_id==52)
		{
			byfzlb=true;
		}
		console.log('service_category_id:'+res.data.data.service.service_category_id);
        that.setData({
          order: res.data.data,
          address_id: res.data.data.address_id,
          service_category_id: res.data.data.service.service_category_id,
		      retentionlist:res.data.data.retentionlist,
			  fwpc:fwpc,
			  fwsj:fwsj,
			  byfzlb:byfzlb
        // ffac:ffac
        })
        if (res.data.data.service.service_time_type == 1 || res.data.data.service.service_time_type == 3) {
          //固定时长
          that.setData({
            service_multiple: false,
            service_time_unit: 30
          })
        } else {
          that.setData({
            service_multiple: true,
            service_time_unit: res.data.data.service.service_time_unit
          })
        }
        that.getTimelist();
      }
    })
  },
  payOrderMsg:function(){
	  var that = this;
	  wx.requestSubscribeMessage({
      tmplIds: [
	  		'WCOeBpOwto_yU4ZM-hUmQePvbfY_lxKyaFK5Yi7nzao', //新订单通知
	  		'Cafgw0abMBtNXSJq8BDKhM_cNk0gydfQ845IywRo7KU', //报价更新通知
	  		'SOnJPXow5f0XddOr1jQ-3wdd6V1SifOHJMdQtPbJNo0' //被用户选择通知
	    ],
	    success: (res) => {
	  	  console.log(res)
	      that.payOrder(that);
	    },
	    fail: (res) => {
	  	    console.log(res)
	      that.payOrder(that);
	    },
	  })
  },


  bindPickerChange: function(e) {
  		  var that = this;
    this.setData({
      index: e.detail.value
    })
  		that.data.good = that.data.pxarray[e.detail.value];
  },

  payOrder: function (that) {
    // var that = this;
    if (that.data.id == 0) {
      wx.showToast({
        title: '参数错误',
        icon: "none"
      })
      return false;
    }
    //判断地址信息
    if (that.data.address_id == 0) {
      wx.showToast({
        title: '请选择服务地址',
        icon: "none"
      })
      return false;
    }
    //判断服务人员
    if (that.data.order.chose_type == 1) {
      if (that.data.worker_id == 0) {
        wx.showToast({
          title: '请选择服务人员',
          icon: "none"
        })
        return false;
      }
    }

    //判断时间
    if (that.data.reserveTime == 0) {
      wx.showToast({
        title: '请选择服务开始时间',
        icon: "none"
      })
      return false;
    }

	if (that.data.region == 0) {
	  wx.showToast({
	    title: '请选择区域',
	    icon: "none"
	  })
	  return false;
	}
    if (that.data.order.bargain == 1) {
      if (!that.data.service_desc) {
        //  wx.showToast({
        //    title: '请选择输入需求说明',
        //    icon:"none"
        //  })
        //  return false;
      }
    }
    that.setData({
      service_desc_images: that.data.picList
    })

    let param = {
      scoure: 'wxapp',
      token: that.data.token,
      address_id: that.data.address_id,
      worker_id: that.data.worker_id,
      service_id: that.data.id,
      servicenums: 1,
      coupon_id: 0,
      service_start_time: that.data.reserveTime,
      remark: that.data.remark,
      service_desc: that.data.service_desc,
      service_desc_images: that.data.service_desc_images,
      check_contract: that.data.checkContract,
	    retention_amount:that.data.retention_amount,
	    area:that.data.area,
	   region:that.data.region,
	   tax_title:that.data.tax_title,
	   tax_no:that.data.tax_no,
	   goodname:that.data.good,
	   bytype:that.data.bytype,
	   fwpc:that.data.fwpctext,
	   fwsj:that.data.fwsjtext,
     tax_email:that.data.tax_email,
	 service_category_id:that.data.service_category_id
    }

    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
	this.setData({
	    btnshow: false
	})
    request.request(url.createorder, param, url.REQUEST_METHOD_POST).then((res) => {
  
      if (res.data.code == 1) {
        //直接支付成功
        //跳转订单详情页
        let orderId = res.data.data.id;
        if (res.data.data.pay_money > 0) {
          var config = JSON.parse(res.data.data.wxconfig);
          console.log("成功", JSON.parse(res.data.data.wxconfig));
		    wx.showNavigationBarLoading(); 
          wx.requestPayment({
            'timeStamp': config.timestamp,
            'nonceStr': config.nonceStr,
            'package': config.package,
            'signType': config.signType,
            'paySign': config.paySign,
            'success': function (res2) {
              console.log("成功", res2)
			    
              if (res2.errMsg == 'requestPayment:ok') {
                wx.navigateTo({
                 // url: '../order_choose/order_choose?id=' + orderId,
				  url: 'pages/order/issue/issue?id=' + orderId,
                })
                return false;
              }
            },
            'fail': function (res2) {
              console.log("失败", res2)
              wx.navigateTo({
                url: '../order_choose/order_choose?id=' + orderId,
              })
              return false;
            },
            'complete': function (res2) {}
          })
        } else {
          wx.showToast({
            title: '支付成功',
            icon: 'none'
          })
          wx.navigateTo({
            // url: '../order_choose/order_choose?id=' + orderId,
			url: '../../order/issue/issue?id=' + orderId,
          })
          return false;
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  changedesc(e) {
    var desc = e.detail.value;
    this.setData({
      service_desc: desc
    })
  },
  changeremark(e) {
    var remark = e.detail.value;
    this.setData({
      remark: remark
    })
  },
  deleteImg: function (e) {
    var imgs = this.data.imgs;
    var picList = this.data.picList;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    picList.splice(index, 1);
    this.setData({
      imgs: imgs,
      picList: picList
    });
    console.log(picList);
  },
  chooseImg: function (e) {
    var that = this;
    var imgs = this.data.imgs;
    if (imgs.length >= 3) {
      this.setData({
        lenMore: 1
      });
      setTimeout(function () {
        that.setData({
          lenMore: 0
        });
      }, 2500);
      return false;
    }
    var count = 3 - imgs.length;
    if (count < 1) {
      return false;
    }

    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        if (res.errMsg == "chooseImage:ok") {
          wx.showLoading({ //显示loding提示框
            title: '正在上传中...',
          })
          let picList = that.data.picList
          var imgs = that.data.imgs;
          res.tempFilePaths.forEach((item, index) => {
            imgs.push(item)
            that.setData({
              imgs: imgs,
            });
            wx.uploadFile({
              url: url.HttpServerHostAddress + url.uploadpic,
              filePath: item,
              name: 'file',
              formData: {
                token: that.data.token
              },
              success: function (res) {
                let ress = JSON.parse(res.data)
                if (ress.code == 1) {
                  var picList = that.data.picList;
                  picList.push(JSON.parse(res.data).data.url);
                  that.setData({
                    picList: picList,
                  })
                  console.log(picList);
                } else {
                  wx.showToast({
                    title: JSON.parse(res.data).msg,
                    icon: 'none',
                    duration: 3000
                  })
                  return;
                }
              },
              fail: res => {
                console.log(res)
              }
            })
          })
          wx.hideLoading(); //隐藏loading提示框
        }
      }
    });
  },
  choseContract(e) {
    var check = e.currentTarget.dataset.checked;
    this.setData({
      checkContract: check
    })
  },
  choseRegion(e) {
	 const value = e.detail.value;
	 const str = value.join(',');
  	console.log(str);
    this.setData({
      region: str
    })
  },
})